package com.rainwood.material.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.rainwood.material.R;
import com.rainwood.material.net.HttpResponse;
import com.rainwood.material.net.NetBean;
import com.rainwood.material.uitls.ActivityStackManager;
import com.rainwood.material.uitls.LoggerUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * @Author: hhx
 * @Date: 2021/3/4
 * @Des:
 */
public abstract class BaseActivity extends AppCompatActivity implements HttpResponse {

    private Dialog netDialog = null;

    @Override
    protected void onStart() {
        super.onStart();
        LoggerUtils.d(this.getClass().getSimpleName(), "onStart");
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LoggerUtils.d(this.getClass().getSimpleName(), "onCreate");

        setContentView(getLayoutId());
        initSoftKeyboard();
        initView();
        initData();

        ActivityStackManager.getInstance().push(this);
    }


    protected abstract int getLayoutId();

    protected abstract void initView();

    protected abstract void initData();

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);
        hideSoftKeyboard();
    }


    @Override
    protected void onResume() {
        super.onResume();
        LoggerUtils.d(this.getClass().getSimpleName(), "onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LoggerUtils.d(this.getClass().getSimpleName(), "onStop");
    }

    @Override
    protected void onDestroy() {
        ActivityStackManager.getInstance().remove(this);
        super.onDestroy();
        LoggerUtils.d(this.getClass().getSimpleName(), "onDestroy");
    }

    @Override
    public void finish() {
        hideSoftKeyboard();
        super.finish();
        LoggerUtils.d(this.getClass().getSimpleName(), "finish");
        overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);
    }

    /**
     * 设置状态栏背景色
     *
     * @return
     */
    public void setStatusBarBackground(@ColorInt int bgColor) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            getWindow().setStatusBarColor(bgColor);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        ViewGroup parent = (ViewGroup) findViewById(android.R.id.content);
        for (int i = 0, count = parent.getChildCount(); i < count; i++) {
            View childView = parent.getChildAt(i);
            if (childView instanceof ViewGroup) {
                childView.setFitsSystemWindows(true);
                ((ViewGroup) childView).setClipToPadding(true);
            }
        }

        return;
    }


    /**
     * 隐藏软键盘
     */
    private void hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        View view = getCurrentFocus();
        if (view != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (manager != null && manager.isActive(view)) {
                manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 初始化软键盘
     */
    protected void initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView().setOnClickListener(v -> hideSoftKeyboard());
    }

    /**
     * 和 setContentView 对应的方法
     */
    public ViewGroup getContentView() {
        return findViewById(Window.ID_ANDROID_CONTENT);
    }

    MediaType jsonType = MediaType.parse("application/json; charset=utf-8");

    public void addPostRequest(NetBean url, Map<String, Object> map) {
        StringBuffer urlBf = new StringBuffer();
        urlBf.append("https://www.yumukeji.cn/project/car/interface/api.php?").append(url.getUrl());
        LoggerUtils.d("okHttpClient", "url: " + urlBf.toString());
        LoggerUtils.d("okHttpClient", "param: " + JSON.toJSONString(map));

        Request request = new Request.Builder()
                .url(urlBf.toString())
                .post(RequestBody.create(JSON.toJSONString(map), jsonType))
                .tag(url.getTag())
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LoggerUtils.d("okHttpClient", "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onError(e.getMessage());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LoggerUtils.d("okHttpClient", response.protocol() + " " + response.code() + " " + response.message());
                String rep = response.body().string();
                LoggerUtils.d("okHttpClient", "onResponse: " + rep);
                try {
                    JSONObject jsonObject = new JSONObject(rep);
                    Thread thread = Thread.currentThread();
                    String data = jsonObject.getString("data");
                    String warn = jsonObject.getString("warn");
                    int code = jsonObject.getInt("code");
                    int tag = (int) call.request().tag();

                    if (code == 1) {
                        if (!TextUtils.isEmpty(data)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    onSuccess(data, tag);
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    onFail("数据异常",tag);
                                }
                            });
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                onFail("数据异常",tag);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    onError(e.getMessage());
                }


            }
        });
    }


}
